package 数据结构专栏.面试算法;

/**
 * @DESC 请实现一个函数，把字符串 s 中的每个空格替换成"%20"。
 * @Author tzq
 * @Date 2020-04-13 09:52
 **/
public class _面试题05_替换空格 {
    public static void main(String[] args) {
        String s = "We are   happy.";
        System.out.println(new _面试题05_替换空格().replaceSpace(s));
        System.out.println(new _面试题05_替换空格().replaceSpace2(s));

    }

    /**
     * 输入：s = "We are happy."
     * 输出："We%20are%20happy."
     *
     * @param s
     * @return
     */
    public String replaceSpace(String s) {
        int len = s.length();
        char[] array = new char[len * 3];
        int size = 0;
        for (int i = 0; i < len; i++) {
            char c = s.charAt(i);
            if (c == ' ') {
                array[size++] = '%';
                array[size++] = '2';
                array[size++] = '0';
            } else {
                array[size++] = c;
            }
        }


        return new String(array, 0, size);
    }


    /**
     * 函数解决
     *
     * @param s
     * @return
     */
    public String replaceSpace2(String s) {
        if ("" != s && null != s) {
            return s.replace(" ", "%20");
        }
        return "";
    }
}
